<template>
  <div class="uploader-list flex-wrap">
    <div class="image-container mr-16 mb-16" v-for="(item, index) in list" :key="index">
      <img :src="item" class="images-item" />
      <i class="el-icon-circle-close f-24" @click="del(index)"></i>
    </div>
    <el-upload
      v-if="list.length < max"
      class="uploader"
      action=""
      :disabled="isUploading"
      accept="image/jpeg,image/jpg,image/png"
      :show-file-list="false"
      :on-change="fileChange"
      :auto-upload="false">
      <template v-if="isUploading">
        <div class="loading-tips flex-center f-14" style="height: 100%">
          <div>正在上传...</div>
        </div>
      </template>
      <div class="icon flex-center" v-else>
        <i class="el-icon-plus uploader-icon"></i>
      </div>
    </el-upload>
  </div>
</template>
<script>
import { getOssToken } from '@/api/upload';
import OSS from 'ali-oss';
import { cloneDeep } from 'lodash';

export default {
  props: {
    list: Array,
    max: {
      type: Number,
      default: 15,
    },
  },
  data() {
    return {
      isUploading: false,
    };
  },
  methods: {
    fileChange(fileData) {
      this.uploadImage(fileData);
    },
    async uploadImage(fileData) {
      this.isUploading = true;
      const { raw, name } = fileData;
      const result = await getOssToken();
      const {
        accessKeyId, accessKeySecret, securityToken, region, bucketName, endpoint,
      } = result;
      this.ossClient = new OSS({
        accessKeyId,
        accessKeySecret,
        stsToken: securityToken,
        bucket: bucketName,
        endpoint,
        region,
      });
      const { url } = await this.ossClient.put(name, raw);
      this.$emit('update:list', [...this.list, url]);
      this.isUploading = false;
    },
    del(index) {
      const list = cloneDeep(this.list);
      list.splice(index, 1);
      this.$emit('update:list', list);
    },
  },
};
</script>
<style lang="scss" scoped>
  .uploader-list {
    .image-container {
      position: relative;
      width: 120px;
      height: 120px;
      .images-item {
        width: 100%;
        height: 100%;
        border-radius: 6px;
      }
      .el-icon-circle-close {
        position: absolute;
        right: 0;
        top: 0;
        transform: translate(50%, -50%);
        cursor: pointer;
      }
    }
    ::v-deep .el-upload {
      border: 1px dashed #d9d9d9;
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      width: 120px;
      height: 120px;
      &:hover {
        border-color: #409EFF;
      }
      .icon {
        width: 120px;
        height: 120px;
        .uploader-icon {
          font-size: 28px;
          color: #8c939d;
          text-align: center;
        }
      }
    }
  }
</style>
